package com.shimao.celnet.payment.lib;

import com.shimao.celnet.payment.util.FinalUtil;
import net.sf.json.JSONObject;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;


public class SignCheckUtil {

    /**
     * js转化为实体
     *
     * @param <T>
     * @param jsonstr
     * @param cls
     * @return
     */
    public static <T> T json2Obj(String jsonstr, Class<T> cls) {
        JSONObject jo = JSONObject.fromObject(jsonstr);
        T obj = (T) JSONObject.toBean(jo, cls);
        return obj;
    }

    /**
     * md5
     *
     * @param b
     * @return
     */
    public static String md5(byte[] b) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.reset();
            md.update(b);
            byte[] hash = md.digest();
            StringBuffer outStrBuf = new StringBuffer(32);
            for (int i = 0; i < hash.length; i++) {
                int v = hash[i] & 0xFF;
                if (v < 16) {
                    outStrBuf.append('0');
                }
                outStrBuf.append(Integer.toString(v, 16).toLowerCase());
            }
            return outStrBuf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return new String(b);
        }
    }


    /**
     * 判断字符串是否为空
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        if (s == null || "".equals(s.trim()))
            return true;
        return false;
    }

    /**
     * 生成随机码
     *
     * @param n
     * @return
     */
    public static String getValidatecode(int n) {
        Random random = new Random();
        String sRand = "";
        n = n == 0 ? 4 : n;// default 4
        for (int i = 0; i < n; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
        }
        return sRand;
    }

    /**
     * 接口sign验证加密
     *
     * @param params
     * @return
     */
    public static String getMySign(TreeMap<String, String> params, String token) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append(token);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (entry.getValue() != null && entry.getValue().length() > 0) {
                sb.append(entry.getKey()).append(entry.getValue());
            }
        }
        sb.append(token);
        return md5(sb.toString().getBytes("UTF-8"));
    }

    /**
     * 接口sign验证
     *
     * @param param
     * @return
     */
    public static boolean checkMySign(TreeMap<String, String> param, String token) throws Exception {
        if (param != null && !param.isEmpty()) {
            if (!param.containsKey(FinalUtil.HEADER_SIGN))
                return false;
            String sign = param.get(FinalUtil.HEADER_SIGN).toString();
            param.remove(FinalUtil.HEADER_SIGN);
            String mySign = getMySign(param, token);
            System.out.println("----sign----:" + getMySign(param, token).toUpperCase());
            return sign.toLowerCase().equals(mySign.toLowerCase());
        }
        return false;
    }

    /**
     * 接口sign验证
     *
     * @param param
     * @return
     */
    public static String postSign(TreeMap<String, String> param, String token) throws Exception {
        String mySign = "";
        if (param != null && !param.isEmpty()) {
            mySign = getMySign(param, token);
            System.out.println("----sign----:" + getMySign(param, token).toUpperCase());
        }
        return mySign;
    }

    /**
     * 签名
     *
     * @param params
     * @return
     * @throws Exception
     */
    public static String sign(TreeMap<String, String> params, String appkey) throws Exception {
        if (params.containsKey("sign"))//签名明文组装不包含sign字段
            params.remove("sign");
        params.put("key", appkey);
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (entry.getValue() != null && entry.getValue().length() > 0) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        String sign = md5(sb.toString().getBytes("UTF-8"));//记得是md5编码的加签
        params.remove("key");
        return sign;
    }

    public static boolean validSign(TreeMap<String, String> param, String appkey) throws Exception {
        if (param != null && !param.isEmpty()) {
            if (!param.containsKey("sign"))
                return false;
            String sign = param.get("sign").toString();
            String mysign = sign(param, appkey);
            return sign.toLowerCase().equals(mysign.toLowerCase());
        }
        return false;
    }

    /**
     * 物业系统的验证签名规则
     *
     * @param nonce    随机数
     * @param username u用户名
     * @param password 密码
     * @return
     * @throws Exception
     */
    public static String getWySign(String nonce, String username, String password) throws Exception {
        MessageDigest md5 = null;
        byte[] bytes;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ignored) {
            throw new Exception(ignored);
        }
        String signStr = username + ":" + nonce + ":" + password;
        bytes = md5.digest(signStr.getBytes("UTF-8"));
        StringBuilder sign = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
